package club.zhcs.task.init;

import java.util.List;

import org.nutz.dao.Dao;
import org.nutz.dao.util.Daos;
import org.nutz.ioc.Ioc;
import org.nutz.lang.ContinueLoop;
import org.nutz.lang.Each;
import org.nutz.lang.ExitLoop;
import org.nutz.lang.Lang;
import org.nutz.lang.LoopException;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.NutConfig;
import org.nutz.mvc.Setup;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;

import club.zhcs.task.bean.Task;
import club.zhcs.task.dao.ITaskDao;
import club.zhcs.task.dao.ITaskDetailDao;
import club.zhcs.task.job.CommonJob;

public class Init implements Setup {

	@Override
	public void init(NutConfig nc) {
		final Dao dao = getDao();
		final ITaskDao taskDao = getIocObj("taskDao", ITaskDao.class);
		final ITaskDetailDao taskDetailDao = getIocObj("taskDetailDao", ITaskDetailDao.class);
		Daos.createTablesInPackage(dao, "club.zhcs.task.bean", false);

		List tasks = taskDao.findAll();

		SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();// 此处可以设置保存数据到数据源
		final Scheduler sched = getScheduler(schedFact);
		Lang.each(tasks, new Each<Task>() {

			@Override
			public void invoke(int index, final Task task, int length) throws ExitLoop, ContinueLoop, LoopException {
				JobDetail job = JobBuilder.newJob().withIdentity(task.getName()).ofType(CommonJob.class)
						.setJobData(new JobDataMap(NutMap.NEW().addv("task", task).addv("taskDetailDao", taskDetailDao))).build();
				Trigger trigger = TriggerBuilder.newTrigger().withIdentity("CommonJobTrigger_" + task.getId()).startNow()
						.withSchedule(CronScheduleBuilder.cronSchedule(task.getCron())).build();// 表达式调度

				try {
					sched.scheduleJob(job, trigger);
				} catch (SchedulerException e) {
					e.printStackTrace();
				}
			}
		});
		try {
			sched.start();
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

	private Scheduler getScheduler(SchedulerFactory schedFact) {
		try {
			return schedFact.getScheduler();
		} catch (SchedulerException e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public void destroy(NutConfig nc) {

	}

	protected Dao getDao() {
		return getIocObj("dao", Dao.class);
	}

	protected <T> T getIocObj(String name, Class<T> clazzOfK) {
		return getIoc().get(clazzOfK, name);
	}

	protected Ioc getIoc() {
		return Mvcs.getIoc();
	}

}
